/**
 * HomeScreen.js
 * 
 * 应用程序的主屏幕组件，负责获取和显示用户的当前位置信息
 * 使用Expo Location API进行位置服务的请求和地理编码
 */

// 导入React核心库和Hook
import React, { useEffect, useState } from 'react'
// 导入React Native基础组件
import { StyleSheet, Text, View, Alert, Pressable, Image, TextInput, ScrollView } from 'react-native'
// 导入安全区域组件，确保内容不被设备刘海、下巴等遮挡
import { SafeAreaView } from 'react-native-safe-area-context'
// 导入Expo的位置服务API
import * as Location from 'expo-location';
import { Feather, MaterialIcons } from '@expo/vector-icons';
import Carousels from '../components/Carousels';
import Services from '../components/Services';
import DressItem from '../components/DressItem';


/**
 * HomeScreen组件
 * 负责显示用户位置信息的主屏幕
 */
const HomeScreen = () => {

    // 状态变量：用于存储和显示当前地址信息
    const [displayCurrentAddress, setDisplayCurrentAddress] = useState("我们正在获取您的位置");
    // 状态变量：用于跟踪位置服务是否启用
    const [locationServicesEnabled, setLocationServicesEnabled] = useState(false);

    /**
     * useEffect Hook
     * 组件挂载时执行，用于检查位置服务状态并获取当前位置
     * 依赖项为空数组，确保只在组件首次渲染时执行一次
     */
    useEffect(() => {
        // 检查设备位置服务是否启用
        checkIfLocationEnabled();
        // 获取设备的当前位置信息
        getCurrentLocation();
    }, []);


    /**
     * 检查设备位置服务是否启用
     * 如果未启用，显示提示对话框
     * @async
     * @function checkIfLocationEnabled
     */
    const checkIfLocationEnabled = async () => {
        // 请求Expo Location API检查位置服务是否启用
        let enabled = await Location.hasServicesEnabledAsync();
        if (!enabled) {
            // 如果位置服务未启用，显示警告对话框
            Alert.alert(
                "位置服务已关闭",
                "请开启位置服务以使用此功能",
                [
                    {
                        text: "取消",
                        onPress: () => console.log("取消"),
                        style: "cancel"
                    },
                    {
                        text: "确定",
                        onPress: () => console.log("确定")
                    }
                ],
                { cancelable: false }
            )
        } else {
            // 更新位置服务启用状态
            setLocationServicesEnabled(enabled)
        }
    }


    /**
     * 获取用户当前位置信息
     * 包括请求位置权限、获取经纬度坐标、反向地理编码转换为地址
     * @async
     * @function getCurrentLocation
     */
    const getCurrentLocation = async () => {
        // 请求前台位置权限
        let { status } = await Location.requestForegroundPermissionsAsync()

        // 如果权限被拒绝，显示提示对话框
        if (status !== "granted") {
            Alert.alert(
                "权限被拒绝",
                "请允许该应用使用定位服务",
                [
                    {
                        text: "Cancel",
                        onPress: () => console.log("Cancel Pressed"),
                        style: "cancel"
                    },
                    {
                        text: "OK",
                        onPress: () => console.log("OK Pressed")
                    }
                ],
                {
                    cancelable: false
                }
            );
            return;
        }

        // 获取当前位置的坐标信息
        const { coords } = await Location.getCurrentPositionAsync();
        // console.log('地址 --> ', coords)

        // 如果成功获取到坐标，进行反向地理编码
        if (coords) {
            const { latitude, longitude } = coords;

            // [{
            //     "city": "临沂市",
            //     "country": "中国",
            //     "district": "兰山区",
            //     "formattedAddress": "山东省临沂市兰山区银雀山街道开阳路90号",
            //     "isoCountryCode": "CN",
            //     "name": null,
            //     "postalCode": null,
            //     "region": "山东省",
            //     "street": "开阳路",
            //     "streetNumber": "90号",
            //     "subregion": "银雀山街道",
            //     "timezone": null
            // }]
            // 将经纬度转换为地址信息
            let response = await Location.reverseGeocodeAsync({
                latitude,
                longitude
            });

            // console.log('解析地址 --> ', response)

            // 处理地理编码响应，更新地址显示
            for (let item of response) {
                // let address = `${item.name}${item.city}${item.postalCode}`;
                // let address = `${item.formattedAddress}`;
                let address = `${item.region}-${item.city}-${item.district}-${item.street}${item.streetNumber}`;
                setDisplayCurrentAddress(address)
            }
        }
    }


    const services = [
        {
            id: "11",
            image: "https://cdn-icons-png.flaticon.com/128/892/892458.png",
            name: "T-shirt",
            quantity: 0,
            price: 10,
        },
        {
            id: "12",
            image: "https://cdn-icons-png.flaticon.com/128/9609/9609161.png",
            name: "dresses",
            quantity: 0,
            price: 10,
        },
        {
            id: "13",
            image: "https://cdn-icons-png.flaticon.com/128/599/599388.png",
        },
        {
            "id": "15",
            "image": "https://cdn-icons-png.flaticon.com/128/3345/3345397.png",
            "name": "shorts",
            "quantity": 0,
            "price": 10
        },
        {
            "id": "16",
            "image": "https://cdn-icons-png.flaticon.com/128/293/293241.png",
            "name": "Sleeveless",
            "quantity": 0,
            "price": 10
        }
    ];


    /**
     * 组件渲染函数
     * 显示屏幕内容
     * @returns {JSX.Element} 屏幕UI组件
     */
    return (
        <ScrollView style={{ backgroundColor: "#F0F0F0", flex: 1, paddingTop: 40 }}>

            {/* 位置 和 个人中心 */}
            <View style={{ flexDirection: "row", alignItems: "center", padding: 8 }}>
                <MaterialIcons name="location-on" size={24} color="#fd5c63" />
                <View>
                    <Text style={{ fontSize: 15, fontWeight: "600" }}>地址</Text>
                    <Text style={{ fontSize: 13 }}>{displayCurrentAddress}</Text>
                </View>
                <Pressable style={{ marginLeft: "auto", marginRight: 7 }}>
                    <Image
                        style={{ width: 40, height: 40, borderRadius: 20 }}
                        source={{
                            uri: "https://i1.hdslb.com/bfs/face/a704e5900c7b63cf8b8aec7e30f27a081f08cf4b.jpg@56w_56h.jpg"
                        }}
                    />
                </Pressable>
            </View>

            {/* 搜索 */}
            <View
                style={{
                    paddingLeft: 6,
                    paddingRight: 6,
                    margin: 8,
                    flexDirection: "row",
                    alignItems: "center",
                    justifyContent: "space-between",
                    borderWidth: 0.8,
                    borderColor: "#d1cfcfff",
                    borderRadius: 8
                }}
            >
                <TextInput placeholder="关键词" />
                <Feather name="search" size={24} color="black"></Feather>
            </View>

            {/* 图片 轮播 */}
            <Carousels></Carousels>


            {/* 服务 */}
            <Services></Services>

            {/*  */}
            {services.map((item, index) => (
                <DressItem item={item} key={index}/>
            ))}



        </ScrollView>
    )
}

// 导出HomeScreen组件作为默认导出
export default HomeScreen

/**
 * 样式定义
 * 使用StyleSheet.create创建组件样式
 */
const styles = StyleSheet.create({

})